// 简单本地聊天存储：记录每个会话的历史与最近会话

const STORAGE_PREFIX = 'chat_history'

function getConversationKey(currentUserId, otherUserId) {
  if (!currentUserId || !otherUserId) return null
  return `${STORAGE_PREFIX}_${currentUserId}_${otherUserId}`
}

function getConversationListKey(currentUserId) {
  if (!currentUserId) return null
  return `chat_conversations_${currentUserId}`
}

export function appendMessage(currentUserId, otherUserId, message) {
  const key = getConversationKey(currentUserId, otherUserId)
  if (!key) return
  const list = uni.getStorageSync(key) || []
  list.push(message)
  const MAX = 500
  const trimmed = list.length > MAX ? list.slice(list.length - MAX) : list
  uni.setStorageSync(key, trimmed)

  // 维护会话列表
  const listKey = getConversationListKey(currentUserId)
  if (listKey) {
    const ids = uni.getStorageSync(listKey) || []
    if (!ids.includes(otherUserId)) {
      ids.unshift(otherUserId)
      uni.setStorageSync(listKey, ids)
    }
  }
}

export function getHistory(currentUserId, otherUserId) {
  const key = getConversationKey(currentUserId, otherUserId)
  const list = key ? (uni.getStorageSync(key) || []) : []
  return list.sort((a, b) => a.timestamp - b.timestamp)
}

export function getRecentConversations(currentUserId) {
  const listKey = getConversationListKey(currentUserId)
  if (!listKey) return []
  const ids = uni.getStorageSync(listKey) || []
  const convs = ids.map(id => {
    const history = getHistory(currentUserId, id)
    if (history && history.length > 0) {
      return { userId: id, latest: history[history.length - 1] }
    }
    return null
  }).filter(Boolean)
  return convs.sort((a, b) => (b.latest.timestamp - a.latest.timestamp))
}